package com.lcc.lynx.security.aspect;

import com.lcc.lynx.security.annotation.Permission;
import com.lcc.lynx.common.exception.e.UnauthorizedException;
import com.lcc.lynx.security.Session;
import com.lcc.lynx.security.annotation.NoAuthorization;
import com.lcc.lynx.security.pojo.UserInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;

//@Component
//@Aspect
public class PermissionAspect {

    @Pointcut("@annotation(com.lcc.lynx.security.annotation.Permission)")
    public void permissionPointCut(){

    }

    //处理完请求前
    @Before("permissionPointCut()")
    public void doBefore(JoinPoint joinPoint){

        UserInfo loginUser = Session.getUserInfo();
        if(loginUser != null && loginUser.isAdmin()){
            return;
        }
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Class<?> controllerClass = joinPoint.getTarget().getClass();
        Permission psn = method.getAnnotation(Permission.class);

        if(psn == null){
            return;
        }
        if(controllerClass.getAnnotation(NoAuthorization.class) != null || method.getAnnotation(NoAuthorization.class) != null){
            return;
        }

        if(loginUser == null || loginUser.getPermissions() == null){
            throw new UnauthorizedException("未授权访问");
        }

        String[] values = psn.value();

        for (String value : values) {
            if(value.startsWith(":")){
                // 获取权限前缀
                Permission permission = controllerClass.getAnnotation(Permission.class);
                if(permission != null){
                    value = permission.value() + value;
                }else{
                    // 没有前缀用reqMapping当前缀
                    RequestMapping reqMapping = controllerClass.getAnnotation(RequestMapping.class);
                    if(reqMapping != null && reqMapping.value().length > 0){
                        String str = reqMapping.value()[0];
                        if(str.startsWith("/")){
                            str = str.substring(1);
                        }
                        value = str.replace("/",":") + value;
                    }
                }
            }
            if(loginUser.getPermissions().contains(value)){
                return;
            }
            throw new UnauthorizedException("未授权访问："+value);
        }
    }
}
